<template>
    <div id="GameSceneView" style="position: relative;">
        <div id="CanvasAmap" style="display: none;"></div>
        <div id="CesiumContainer"></div>
        <div id="EnableContainer"></div>
        <!-- <canvas id="CanvasKriging" style="display: '';"></canvas> -->

        <div class="GameSceneStatusUI">
            <div v-for="item in tip_images" class="ui_status-item">
                <img style="width: 20px; margin-right: 6px;" :src="item.img" alt="" srcset="">
                <n-progress style="opacity: 1;" type="line" :percentage="item.progress" :show-indicator="false"
                    :color="{ stops: ['white', 'grey'] }" />
            </div>
        </div>

        <div class="GameSceneCameraUI">
            <div v-for="item in camera_images" @click="f_camera(item)" class="ui_camera-item">
                <img style="width: 20px; margin-right: 6px;" :src="item.img" alt="" srcset="">
                <span>{{ item.name }}</span>
            </div>
        </div>

        <div class="GameSceneBuildUI">
            <div v-for="item in build_images" class="ui_build-item">
                <img style="width: 18px; margin-right: 6px;" :src="item.img" alt="" srcset="">
                <span v-if="item.type === 'countdown'" style="font-variant-numeric: tabular-nums; white-space: nowrap">
                    <n-countdown :duration="countdown" />
                </span>
                <span v-if="item.type === 'count_stone'"
                    style="font-variant-numeric: tabular-nums; white-space: nowrap">
                    {{ count_stone }}
                </span>
                <span v-if="item.type === 'count_wood'" style="font-variant-numeric: tabular-nums; white-space: nowrap">
                    {{ count_wood }}
                </span>
            </div>
        </div>

        <div v-if="showBackPackUI" class="GameSceneBackPackUI">
            <div class="game-ui-title">
                背包
            </div>
            <div class="backPack-ui">
                <div v-for="(item, index) in backPackItems" :key="index" :class="item.className">
                    <n-popover :style="{
                        width: '160px',
                        height: '210px',
                        backgroundColor: '#1a1a1a',
                        border: item.describe.bor,
                        boxShadow: '0 0 10px rgba(0, 0, 0, 0.7)'
                    }
                        " placement="right-start" trigger="click" scrollable :show-arrow="false">
                        <template #trigger>
                            <div>
                                <div v-if="item.classNameOth" class="backPackItems-legend-border-left"></div>
                                <div v-if="item.classNameOth" class="backPackItems-legend-border-right"></div>
                                <img style="display: block; width: 31px;" :src="item.image" alt="Equ" srcset="">
                            </div>
                        </template>

                        <div :style="{ color: item.describe.title.col }" class="backpackDescribe-title">{{
                            item.describe.title.txt }}</div>
                        <div class="backpackDescribe-type">{{ item.describe.type.txt }}</div>
                        <div class="backpackDescribe-description">
                            {{ item.describe.des.txt }}
                        </div>
                        <n-tag @click="useClickPackItems(1, item.describe.title)" v-if="item.describe.showUse"
                            style="font-size: 10px; margin-top: 12px; margin-right: 6px;" type="success">
                            <span style="color: #ffffff; font-weight: bold;">食用</span>
                        </n-tag>
                        <n-tag @click="useClickPackItems(2, item.describe.title)" v-if="item.describe.showSell"
                            style="font-size: 10px; margin-top: 12px; margin-left: 6px;" type="error">
                            <span style="color: #ffffff; font-weight: bold;">卖出</span>
                        </n-tag>
                        <div class="backpackDescribe-value">价值: {{ item.describe.val }} 金币</div>
                    </n-popover>
                </div>
            </div>
            <div class="game-ui-btn">
                <span @click="closeFormUI">关闭</span>
            </div>
        </div>

        <n-modal v-model:show="showModal" :title="title" :mask-closable="false" preset="dialog" :content="content"
            positive-text="确认" @positive-click="onPositiveClick" />
    </div>
</template>

<script setup>
import { onMounted, ref, nextTick } from 'vue';
import { CesiumMain, EnableGameWorldSceneMain, EnableGameWorldSceneInit } from '@/components';
import { enable3d, Canvas } from '@enable3d/phaser-extension';
import { SceneVueInteractiveSubscription } from '@/utils/SceneVueInteractiveSubscription';
import proxy from '@/config/host';
import Phaser from 'phaser';

import { NProgress, NCountdown, NModal, NPopover, NTag } from 'naive-ui';
import axios from 'axios';



const title = ref('');
const content = ref('');
const showModal = ref(false);
const onPositiveClick = () => {
    switch (title.value) {
        case '安全屋 [木材: 50 石头: 100]':
            SceneVueInteractiveSubscription.publish('open_building_timer');
            break;
    };
};


const showBackPackUI = ref(false);
const backPackItems = ref([]);
SceneVueInteractiveSubscription.subscribe('ui_open_backpack', puid => {
    axios.get(`${proxy.development.API}/api/v1/temp_api/game/backpack?playerUID=${puid}`)
        .then(response => {
            if (response.data.code === 200) {
                nextTick(() => {
                    backPackItems.value = response.data.msg.flat();

                    showBackPackUI.value = true;
                });
            };
        })
        .catch(error => {
            console.error('Error:', error);
        });
});
const useClickPackItems = (sw, name) => {
    const puid = WV_PUID;
    switch (name.txt) {
        case '饮料':
            API('soda', 'ui-status-item-VuJEkVkD', puid, 1);
            break;
        case '牛油果':
            API('advocado', 'ui-status-item-jqHWPeAq', puid, 1);
            break;
        case '晚餐':
            API('dinner', 'ui-status-item-jqHWPeAq', puid, 5);
            break;
    }
};
const closeFormUI = () => {
    showBackPackUI.value = false;
    backPackItems.value = [];
};
const API = (type, id, puid, number) => {
    axios.post(`${proxy.development.API}/api/v1/temp_api/game/playersEatFood`, {
        playerUID: puid,
        type: type
    }).then(async response => {
        if (response.data.code === 200) {
            const _response = await axios.get(`${proxy.development.API}/api/v1/temp_api/game/backpack?playerUID=${puid}`);
            if (_response.data.code === 200) {
                nextTick(() => {
                    backPackItems.value = _response.data.msg.flat();

                    feAdd(id, number, () => {
                        console.log('player die!');
                    });
                });
            };
        };
    }).catch(error => {
        console.error('Error:', error);
    });
};


const tip_images = ref([]);
const getUiStatusTipImageItem = () => {
    return new Promise((resolve, reject) => {
        axios.get(`${proxy.development.API}/api/v1/temp_api/game/getUiStatusTipImageItem`)
            .then(response => {
                if (response.data.code === 200) {
                    tip_images.value = response.data.message;

                    resolve();
                };
            })
            .catch(error => {
                console.error('Error:', error);
                reject(error);
            });
    });
};

const camera_images = ref([]);
const f_camera = (e) => {
    switch (e.id) {
        case 'ui-camera-item-imDN1z':
            SceneVueInteractiveSubscription.publish('ui_camera', 1);
            break;
        case 'ui-camera-item-h58zJm':
            SceneVueInteractiveSubscription.publish('ui_camera', 2);
            break;
        case 'ui-camera-item-kKZpYH':
            SceneVueInteractiveSubscription.publish('ui_camera', 4);
            break;
    };
};
const getUiCameraSwitchImageItem = () => {
    return new Promise((resolve, reject) => {
        axios.get(`${proxy.development.API}/api/v1/temp_api/game/getUiCameraSwitchImageItem`)
            .then(response => {
                if (response.data.code === 200) {
                    camera_images.value = response.data.message;

                    resolve();
                };
            })
            .catch(error => {
                console.error('Error:', error);
                reject(error);
            });
    });
};

const build_images = ref([]);
const getUiBuildImageItem = () => {
    return new Promise((resolve, reject) => {
        axios.get(`${proxy.development.API}/api/v1/temp_api/game/getUiBuildImageItem`)
            .then(response => {
                if (response.data.code === 200) {
                    build_images.value = response.data.message;

                    resolve();
                };
            })
            .catch(error => {
                console.error('Error:', error);
                reject(error);
            });
    });
};

const listenStartGame = () => {
    /**@description Event */
    SceneVueInteractiveSubscription.subscribe('open_ui_status', () => {
        listenGameSceneEvent();
        listenGameIndustryCount();
        listenGameBuildCountDown();
    });
};

const listenGameSceneEvent = () => {
    /**@description Event */
    SceneVueInteractiveSubscription.subscribe('ui_status_air', num => {
        tip_images.value.forEach(item => {
            if (item.id === 'ui-status-item-qcVdFmaQ') {
                if (num >= 100) {
                    item.progress = 0;
                    SceneVueInteractiveSubscription.publish('OpenAirdrop');
                    return;
                };
                item.progress = num;
            };
        });
    });
};

const countdown = ref(0);
const listenGameBuildCountDown = () => {
    /**@description Event */
    SceneVueInteractiveSubscription.subscribe('build_timer', num => {
        countdown.value = num;
    });
};

const count_stone = ref(0);
const count_wood = ref(0);
const listenGameIndustryCount = () => {
    /**@description Event */
    SceneVueInteractiveSubscription.subscribe('ui_Industry_count', obj => {
        const { wood, stone } = JSON.parse(obj.player_industry_info);
        count_stone.value = stone;
        count_wood.value = wood;
    });
};

const getUrlParams = (url = location.href) => {
    let urlStr = url.split('?')[1] || '';
    let obj = {};
    let paramsArr = urlStr.split('&');
    for (let i = 0, len = paramsArr.length; i < len; i++) {
        const num = paramsArr[i].indexOf('=');
        let arr = [paramsArr[i].substring(0, num), paramsArr[i].substring(num + 1)];
        obj[arr[0]] = arr[1];
    }
    return obj;
};


let FalloutProgressTimer = null;
let StomachProgress = null;
let SodaProgress = null;
const fe = (id, callback) => {
    tip_images.value.forEach(item => {
        if (item.id === id) {
            if (item.progress <= 0) {
                item.progress = 0;
                callback(1);
                return;
            };
            item.progress -= 5;
        };
    });
};
const feAdd = (id, num, callback) => {
    tip_images.value.forEach(item => {
        if (item.id === id) {
            if (item.progress >= 100) return;
            if (item.progress <= 0) {
                item.progress = 0;
                callback(1);
                return;
            };
            item.progress += num;
        };
    });
};
const openTimer = (obj) => {
    FalloutProgressTimer = setInterval(() => {
        fe('ui-status-item-pawZggVy', () => {
            clearInterval(FalloutProgressTimer);
            FalloutProgressTimer = null;
        });
    }, obj.fallout_ms);

    StomachProgress = setInterval(() => {
        fe('ui-status-item-jqHWPeAq', () => {
            clearInterval(StomachProgress);
            StomachProgress = null;
        });
    }, obj.stomach_ms);

    SodaProgress = setInterval(() => {
        fe('ui-status-item-VuJEkVkD', () => {
            clearInterval(SodaProgress);
            SodaProgress = null;
        });
    }, obj.soda_ms);
};



/**@description Event */
SceneVueInteractiveSubscription.subscribe('ui_open_building', async puid => {
    const response = await axios.post(`${proxy.development.API}/api/v1/temp_api/game/playersBuildingStatus`, {
        playerUID: puid,
        type: ''
    });
    const data = JSON.parse(response.data.message.player_status_build);
    if (data.playerBuild === 0.2) {
        title.value = '安全屋 [木材: 50 石头: 100]';
        content.value = '是否要建造你的安全屋？';
        showModal.value = true;
    } else {
        console.log('安全屋建造完成，可以进入');
        EnableGameWorldSceneInit.WoodsScene(() => {
            SceneVueInteractiveSubscription.publish('enable3d_switch_scene', 'tent_detailedOpen.glb');
        });
    };
});

/**@description Event */
SceneVueInteractiveSubscription.subscribe('ui_status_player', obj => {
    const { falloutProgress, sodaProgress, stomach } = JSON.parse(obj.players_status_info).cronJob.uiStatus;
    tip_images.value.forEach(item => {
        if (item.id === 'ui-status-item-pawZggVy') {
            item.progress = falloutProgress;
        };
        if (item.id === 'ui-status-item-jqHWPeAq') {
            item.progress = stomach;
        };
        if (item.id === 'ui-status-item-VuJEkVkD') {
            item.progress = sodaProgress;
        };
    });

    axios.get(`${proxy.development.API}/api/v1/temp_api/game/getUiStatusTimer`)
        .then(response => {
            if (response.data.code === 200) {

                openTimer(response.data.message.ui_status);
            };
        })
        .catch(error => {
            console.error('Error:', error);
            reject(error);
        });

});

/**@description Event */
SceneVueInteractiveSubscription.subscribe('ui_build_message', message => {
    console.log(message);
});

/**@description Event */
SceneVueInteractiveSubscription.subscribe('ui_build_done', message => {
    console.log(message);
});



/**@description Event */
SceneVueInteractiveSubscription.subscribe('get_wv_puid', () => {
    SceneVueInteractiveSubscription.publish('res_wv_puid', WV_PUID);
});

let WV_PUID = null;
onMounted(async () => {
    const url = getUrlParams();
    console.log('puid', url.playerUID);

    /**@description {pro} */
    if (!url.playerUID) return;

    WV_PUID = url.playerUID;
    
    /**
     * @var
     * cesium canvas init
     */
    const canvas_ces = document.getElementById('CesiumContainer');
    /**
     * @var
     * enable canvas init
     */
    const canvas_enable = document.getElementById('EnableContainer');

    let conf = {
        type: Phaser.WEBGL,
        width: window.innerWidth,
        height: window.innerHeight,
        transparent: true,
        parent: 'EnableContainer',
        scale: {
            mode: Phaser.Scale.FIT,
            autoCenter: Phaser.Scale.CENTER_BOTH,
            width: window.innerWidth * Math.max(1, window.devicePixelRatio / 2),
            height: window.innerHeight * Math.max(1, window.devicePixelRatio / 2)
        },
        scene: [
            EnableGameWorldSceneMain
        ],
        ...Canvas()
    };
    enable3d(() => new Phaser.Game(conf)).withPhysics(`${proxy.development.STATIC_API}${proxy.development.PATH_AMMO}`);

    /**
     * @var
     * kriging canvas init
     */
    // const canvas_krig = document.getElementById('CanvasKriging');
    /**
     * @var
     * amap canvas init
     */
    const canvas_amap = document.getElementById('CanvasAmap');

    /**
     * @function
     * -get ui status
     */
    await getUiStatusTipImageItem();

    /**
     * @function
     * -get ui camera
     */
    await getUiCameraSwitchImageItem();

    /**
     * @function
     * -get ui build
     */
    await getUiBuildImageItem();

    /**
     * @var
     * cesium main
     */
    const c = new CesiumMain("CesiumContainer", true, false, false, { tdServer: false, type: 'vec_w', tag: 'cva_w' }, { amapServer: true, center: [null, null], can: canvas_amap }, '', canvas_ces, canvas_enable);
    await c.CameraController({
        Ro: false,
        Tr: false,
        Zo: false,
        Ti: false,
        Lo: false
    });

    listenStartGame();

});

</script>

<style scoped>
.GameSceneView {
    position: absolute;
    z-index: 2;
    left: 20px;
    top: 20px;
}

#CesiumContainer {
    width: 100vw;
    height: 100vh;
    margin: 0;
    padding: 0;
    overflow: hidden;
}

#EnableContainer {
    width: 100vw;
    height: 100vh;
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
}

.GameSceneStatusUI {
    position: absolute;
    z-index: 3;
    top: 2%;
    left: 50%;
    display: flex;
    align-items: center;
    transform: translate(-50%, 0);
}

.GameSceneCameraUI {
    position: absolute;
    z-index: 3;
    bottom: 2%;
    left: 50%;
    display: flex;
    align-items: center;
    transform: translate(-50%, 0);
}

.GameSceneBuildUI {
    position: absolute;
    z-index: 3;
    top: 8%;
    left: 50%;
    display: flex;
    align-items: center;
    transform: translate(-50%, 0);
}

.ui_status-item {
    width: 100px;
    display: flex;
    align-items: center;
    margin-right: 12px;
}

.ui_camera-item {
    display: flex;
    align-items: center;
    margin: 0 10px 0 10px;
    font-weight: bold;
    color: #514f4f;
}

.ui_build-item {
    display: flex;
    align-items: center;
    margin: 0 10px 0 10px;
    font-weight: bold;
    color: #514f4f;
}

.GameSceneBackPackUI {
    position: absolute;
    z-index: 1;
    width: 400px;
    height: 220px;
    padding: 20px;
    background: rgba(20, 20, 40, 0.8);
    border: 2px solid #4a8cff;
    border-radius: 8px;
    box-shadow: 0 0 15px rgba(74, 140, 255, 0.5),
        inset 0 0 10px rgba(74, 140, 255, 0.3);
    color: #fff;
    font-family: 'Arial', sans-serif;
    overflow: hidden;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

.GameSceneBackPackUI::before {
    top: -2px;
    left: -2px;
    border-right: none;
    border-bottom: none;
}

.GameSceneBackPackUI::after {
    bottom: -2px;
    right: -2px;
    border-left: none;
    border-top: none;
}

.game-ui-title {
    color: #ffffff;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
    letter-spacing: 1px;
}

.backPack-ui {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: stretch;
    padding: 4px;
    height: 124px;
    border: 2px solid rgba(255, 255, 255, .7);
    border-radius: 4px;
    overflow: hidden;
    overflow-y: auto;
}

.backPack-ui::-webkit-scrollbar {
    display: none;
}

.backPack-ui>div {
    margin: 6px;
}

.backPackItems {
    width: 31px;
    height: 31px;
    position: relative;
    background-color: rgba(0, 0, 0, 0.2);
    box-sizing: border-box;
    border-radius: 1px;
    box-shadow: 0 0 10px rgba(0, 255, 0, 0.5);
}

.backPackItems-legend {
    width: 31px;
    height: 31px;
    position: relative;
    background-color: rgba(0, 0, 0, 0.2);
    box-sizing: border-box;
    border-radius: 1px;
    box-shadow: 0 0 10px rgba(0, 255, 0, 0.5);
}

/* 水平渐变动画（上下边框） */
@keyframes rainbow-horizontal {
    0% {
        background-position: 0% 50%;
    }

    100% {
        background-position: 100% 50%;
    }
}

/* 垂直渐变动画（左右边框） */
@keyframes rainbow-vertical {
    0% {
        background-position: 0% 0%;
    }

    100% {
        background-position: 0% 100%;
    }
}

.backPackItems-legend::before,
.backPackItems-legend::after {
    content: '';
    position: absolute;
    width: 100%;
    height: 1px;
    background-image: linear-gradient(to right, red, yellow, green, blue, violet);
    background-size: 500% 100%;
    border-radius: 5px;
    animation: rainbow-horizontal 2s linear infinite;
}

.backPackItems-legend::before {
    top: 0;
}

.backPackItems-legend::after {
    bottom: 0;
}

.backPackItems-legend-border-left,
.backPackItems-legend-border-right {
    position: absolute;
    top: 1px;
    bottom: 1px;
    width: 1px;
    background-image: linear-gradient(to bottom, red, yellow, green, blue, violet);
    background-size: 100% 500%;
    border-radius: 5px;
    animation: rainbow-vertical 2s linear infinite;
}

.backPackItems-legend-border-left {
    left: 0;
}

.backPackItems-legend-border-right {
    right: 0;
}

.backpackDescribe-title {
    font-size: 16px;
    font-weight: bold;
    text-shadow: 0 0 5px rgba(241, 196, 15, 0.5);
    margin-bottom: 10px;
    padding-bottom: 5px;
    border-bottom: 1px solid #8a6d3b;
}

.backpackDescribe-type {
    font-size: 10px;
    color: #a4a4a4;
    margin-bottom: 10px;
}

.backpackDescribe-description {
    font-style: italic;
    padding: 10px;
    background-color: rgba(0, 0, 0, 0.3);
    border-left: 3px solid #8a6d3b;
}

.backpackDescribe-description {
    font-style: italic;
    padding: 10px;
    background-color: rgba(0, 0, 0, 0.3);
    border-left: 3px solid #8a6d3b;
}

.backpackDescribe-value {
    font-size: 10px;
    margin-top: 10px;
    text-align: right;
    color: #6df10f;
    font-weight: bold;
}

.game-ui-btn {
    float: right;
    margin-top: 4px;
}

.game-ui-btn>span {
    color: #ffffff;
    font-size: 14px;
}

:deep(.cesium-infoBox-title) {
    height: 100%;
}

:deep(.cesium-viewer-bottom) {
    display: none !important;
}

:deep(.cesium-viewer-toolbar) {
    display: none !important;
}
</style>